<template>
  <div>
    <el-form
      v-if="selectedId"
      :model="optionModel"
      size="mini"
      label-position="left"
      label-width="120px"
      class="setting-form"
      @submit.native.prevent
    >
      <el-collapse v-model="unitActiveCollapseNames" class="setting-collapse">
        <el-collapse-item
          v-if="onShowCollapse.commonProps"
          name="1"
          :title="'常见属性'"
        >
          <template v-for="propName in hasProperty.commonProps">
            <component
              :is="commonProps[propName]"
              :key="propName"
              :option-model="optionModel"
              :designer="designer"
            />
          </template>
        </el-collapse-item>

        <el-collapse-item
          v-if="onShowCollapse.advProps"
          name="2"
          :title="'高级属性'"
        >
          <template v-for="propName in hasProperty.advProps">
            <component
              :is="advProps[propName]"
              :key="propName"
              :option-model="optionModel"
              :designer="designer"
            />
          </template>
        </el-collapse-item>

        <el-collapse-item
          v-if="onShowCollapse.eventProps"
          name="3"
          :title="'事件属性'"
        >
          <template v-for="propName in hasProperty.eventProps">
            <component
              :is="eventProps[propName]"
              :key="propName"
              :option-model="optionModel"
              :designer="designer"
            />
          </template>
        </el-collapse-item>
      </el-collapse>
    </el-form>
  </div>
</template>

<script>
/* eslint-disable vue/require-default-prop */
/* eslint-disable eol-last */
// import CodeEditor from "@/components/code-editor/index";
import PropertyEditors from "./property-editor/index";
import ExtensionEditors from "./extension-load";
import i18n from "Yan/utils/i18n";
import $DialogJs from "Yan/utils/extendDialog";
import EventEditDialog from "./eventEditDialog.vue";
// import { getDifferent } from "@/utils";
import UnitProperties, { propertyRegistered } from "./propertyRegister";
const { COMMON_PROPERTIES, ADVANCED_PROPERTIES, EVENT_PROPERTIES } =
  UnitProperties;
export default {
  componentName: "unitSetting",
  components: {
    // CodeEditor,
    ...PropertyEditors,
    ...ExtensionEditors,
  },
  mixins: [i18n],
  props: {
    designer: Object,
  },
  provide() {
    return {
      // optionModel: this.optionModel,
      selectUnit: () => this.selectUnit,
    };
  },
  data() {
    return {
      unitActiveCollapseNames: ["1", "3"],
      commonProps: COMMON_PROPERTIES,
      advProps: ADVANCED_PROPERTIES,
      eventProps: EVENT_PROPERTIES,

      showUnitEventDialogFlag: false,
      eventHandlerCode: "",
      curEvent$Name: "",
      eventHeader: "",

      optionModel: {},
      selectUnit: {},

      onOptionsLoad: false,

      // ======渲染控制器======
      onShowCollapse: {
        commonProps: false,
        advProps: false,
        eventProps: false,
      },
      hasProperty: {
        commonProps: {},
        advProps: {},
        eventProps: {},
      },
    };
  },
  computed: {
    fieldLib() {
      return this.designer.fieldLib;
    },
    selectedId() {
      return this.designer.selectedId;
    },

    optionKeys() {
      return Object.keys(this.optionModel);
    },
  },
  watch: {
    optionModel: {
      handler(n) {
        if (Object.keys(n).length === 0) return;
        if (this.onOptionsLoad) {
          this.onOptionsLoad = false;
          return;
        }
        if (!this.selectedId) return;
        this.designer.setFieldLibOption(n);
      },
      deep: true,
      immediate: true,
    },
    selectedId: {
      handler(n) {
        // console.log("unit setting selectedId =>", n);
        if (!this.designer) return;
        if (n !== null)
          this.resetOptionModel(this.designer.fieldLib[this.selectedId]);
        else {
          this.selectUnit = {};
          // this.optionModel = {};
          this.$set(this, "optionModel", {});
          this.onShowCollapse = {
            commonProps: false,
            advProps: false,
            eventProps: false,
          };
          this.hasProperty = {
            commonProps: {},
            advProps: {},
            eventProps: {},
          };
        }
      },
      immediate: true,
    },
  },
  created() {
    // console.log(COMMON_PROPERTIES, ADVANCED_PROPERTIES, EVENT_PROPERTIES);
    this.$on("editEventHandler", function (eventName, eventParams) {
      this.editEventHandler(eventName, eventParams);
    });

    this.designer.handleEvent("form-css-updated", (cssClassList) => {
      this.designer.setCssClassList(cssClassList);
    });
    this.designer.handleEvent("fieldLib_change", this.resetOptionModel);
  },
  mounted() {
    // console.groupCollapsed("----------检查已注册属性编辑组件----------");
    // console.log("PropertyEditors", PropertyEditors);
    // const allObj = {
    //   ...COMMON_PROPERTIES,
    //   ...ADVANCED_PROPERTIES,
    //   ...EVENT_PROPERTIES,
    // };
    // Object.keys(allObj)
    //   .sort()
    //   .forEach((i) => {
    //     // if (!PropertyEditors[allObj[i]])
    //     console.log(
    //       i,
    //       allObj[i],
    //       !!PropertyEditors[allObj[i]] || !!ExtensionEditors[allObj[i]]
    //     );
    //   });
    // console.groupEnd();
  },
  methods: {
    resetOptionModel(newCon) {
      this.onOptionsLoad = true;
      this.selectUnit = { ...newCon };
      this.$set(this, "optionModel", { ...this.selectUnit.options });
      // console.groupCollapsed(`------加载组件编辑属性 ${newCon.id}------`);
      this.hasProperty = {
        commonProps: this.getHasProperty(this.commonProps, "commonProps"),
        advProps: this.getHasProperty(this.advProps, "advProps"),
        eventProps: this.getHasProperty(this.eventProps, "eventProps"),
      };
      this.onShowCollapse = {
        commonProps: Object.keys(this.hasProperty.commonProps).length > 0,
        advProps: Object.keys(this.hasProperty.advProps).length > 0,
        eventProps: Object.keys(this.hasProperty.eventProps).length > 0,
      };
      // console.groupEnd();
    },
    // 获取当前组件有的属性编辑器
    getHasProperty(propsObj, propsName) {
      if (!propsObj && !propsName) return {};
      const lib = [];
      // console.groupCollapsed(`------propertykey ${propsName}------`);
      Object.keys(this.optionModel).forEach((i) => {
        // console.log(
        //   i,
        //   Object.prototype.hasOwnProperty.call(this.optionModel, i),
        //   propertyRegistered(i),
        //   !!PropertyEditors[propsObj[i]]
        // );
        if (
          Object.prototype.hasOwnProperty.call(propsObj, i) &&
          propertyRegistered(i) &&
          (PropertyEditors[propsObj[i]] || ExtensionEditors[propsObj[i]])
        ) {
          lib.push(i);
          // lib[i] = propsObj[i];
        }
      });
      // if (lib.indexOf("optionItems") !== -1) {
      //   console.log("optionItems", this.optionModel.optionItems);
      // }
      // if (lib.indexOf("colSummeryHandle") > -1) {
      // console.log("colSummeryHandle", lib.indexOf("colSummeryHandle"));
      // lib.splice(lib.indexOf("name"), 1);
      // lib.splice(0, 0, "name");
      // }
      if (lib.indexOf("name") > -1) {
        lib.splice(lib.indexOf("name"), 1);
        lib.splice(0, 0, "name");
      }
      if (lib.indexOf("tableColField") > -1) {
        lib.splice(lib.indexOf("tableColField"), 1);
        lib.splice(1, 0, "tableColField");
      }
      if (lib.indexOf("tableLabel") > -1) {
        lib.splice(lib.indexOf("tableLabel"), 1);
        lib.splice(2, 0, "tableLabel");
      }
      // console.log("getHasProperty", lib);
      // console.groupEnd();
      return lib;
    },
    hasPropEditor(propName, editorName) {
      //   console.log("hasPropEditor", propName, editorName);
      if (!editorName) return false;

      /* alert组件注册了两个type属性编辑器，跳过第一个type属性编辑器，只显示第二个alert-type属性编辑器！！ */
      if (propName.indexOf("-") <= -1) {
        const uniquePropName = this.selectUnit.type + "-" + propName;
        if (propertyRegistered(uniquePropName)) {
          return false;
        }
      }
      // console.log(
      //   "hasPropEditor",
      //   editorName,
      //   Object.prototype.hasOwnProperty.call(this.optionModel, editorName)
      // );

      return Object.prototype.hasOwnProperty.call(this.optionModel, editorName);
    },
    // 判断是否有 对应的属性的字段
    showCollapse(propsObj) {
      //   console.log("showCollapse", propsObj, this.optionModel);
      let result = false;
      for (const propName in propsObj) {
        // console.log(propName);
        if (Object.prototype.hasOwnProperty.call(this.optionModel, propName)) {
          result = true;
          break;
        }
      }
      return result;
    },

    // 编辑组件事件代码
    editEventHandler(eventName, eventParams, eventMode = "javascript") {
      const code =
        eventName === "onValidate" && !this.optionModel["onValidate"]
          ? "  /* sample code */\n  /*\n  if ((value > 100) || (value < 0)) {\n    callback(new Error('error message'))  //fail\n  } else {\n    callback();  //pass\n  }\n  */"
          : this.selectUnit.options[eventName] || "";
      // console.log(
      //   "editEventHandler",
      //   eventName,
      //   this.selectUnit.options[eventName]
      // );
      // console.log(
      //   "editEventHandler1",
      //   eventName === "onValidate",
      //   !this.optionModel["onValidate"]
      // );
      const lib = {};
      Object.keys(this.fieldLib).forEach((i) => {
        if (
          this.fieldLib[i].group === "field" &&
          (!!this.fieldLib[i].options.label ||
            !!this.fieldLib[i].options.tableLabel)
        )
          lib[i] = this.fieldLib[i];
      });

      // console.log(lib);
      $DialogJs(EventEditDialog, {
        selectedId: this.selectedId,
        pluginLib: {
          fieldLib: lib,
        },
        mode: eventMode,
        curEventName: eventName,
        eventHeader: `${this.optionModel.name}.${eventName}(${eventParams.join(
          ","
        )}) {`,
        eventHandlerCode: code,

        onSave: (e, close) => {
          this.optionModel[eventName] = e;
          this.selectUnit.options[eventName] = e;
          close();
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.setting-form {
  ::v-deep .el-form-item__label {
    font-size: 13px;
    //text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }

  ::v-deep .el-form-item--mini.el-form-item {
    margin-bottom: 6px;
  }
}
</style>